package cn.virens.common.boot.rabbit.listener;

import cn.virens.common.boot.rabbit.RabbitMessage;
import cn.virens.common.util.exception.APIException;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.InitializingBean;

import java.io.IOException;

public abstract class AbstractRabbitListener<T> implements ChannelAwareMessageListener, InitializingBean {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void onMessage(Message msg, Channel channel) throws IOException {
        try (RabbitMessage message = new RabbitMessage(msg, channel)) {
            this.onHandler(message.getBody(getClazz()), message);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }
    }

    /**
     * 目标对象Class
     *
     * @return
     */
    protected abstract Class<T> getClazz();

    /**
     * 消息处理
     *
     * @param message 消息信息
     * @param obj     消息数据
     * @throws APIException
     */
    protected abstract void onHandler(T obj, RabbitMessage message) throws IOException;

}
